import Vue from 'vue'
import VueRouter from 'vue-router'
import common from '@/global/common.js'
import axios from 'axios'

Vue.use(VueRouter)

// 定义路由
const routes = [
  { path: '/', name: 'Index', component: () => import('@/components/Index') },
  { path: '/login', name: 'Login', component: () => import('@/components/login/Login'), },
]

const router = new VueRouter({
  routes // (缩写) 相当于 routes: routes 
})

// https://router.vuejs.org/zh/guide/advanced/navigation-guards.html#全局前置守卫
router.beforeEach((to, from, next) => {
  axios.defaults.headers.common['Authorization'] = localStorage.getItem("authToken")

  let loginComponents = ['Login', 'TokenLogin']
  if (loginComponents.includes(to.name)) {
    next()
    return
  }

  let successCallback = function () { next() } // 进行管道中的下一个钩子
  let failureCallback = function () {
    let routerName = 'Login'
    next({ name: routerName })
  }
  common.sessionCheck('ROUTER', successCallback, failureCallback)
})

export default router